<template>
  <div class="container">
    <div class="card">
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/folder' }">根目录</el-breadcrumb-item>
          <template v-for="(part, index) in breadcrumbParts" :key="index">
            <el-breadcrumb-item :to="getBreadcrumbLink(part, index)" v-if="index < breadcrumbParts.length - 1">
              {{ part.name }}
            </el-breadcrumb-item>
            <el-breadcrumb-item v-else>{{ part.name }}</el-breadcrumb-item>
          </template>
        </el-breadcrumb>
        <div v-if="rootDirectory" class="root-directory-info">
          <el-tag size="small" type="info">已限制在目录: {{ rootDirectory }}</el-tag>
        </div>
      </div>

      <div class="folder-actions">
        <div class="left-actions">
          <el-button type="success" @click="showCreateFolderDialog">
            <el-icon>
              <FolderAdd />
            </el-icon>
            新建文件夹
          </el-button>

          <el-upload class="upload-button" action="#" :http-request="uploadFile" :show-file-list="false"
            :multiple="true">
            <el-button type="primary">
              <el-icon>
                <Upload />
              </el-icon>
              上传
            </el-button>
          </el-upload>

          <el-button type="warning" @click="toggleEditMode">
            <el-icon>
              <Edit />
            </el-icon>
            {{ isEditMode ? '取消编辑' : '编辑' }}
          </el-button>

          <el-button v-if="isEditMode && selectedItems.length > 0" type="danger" @click="confirmDelete">
            <el-icon>
              <Delete />
            </el-icon>
            删除 ({{ selectedItems.length }})
          </el-button>
        </div>

        <div class="right-actions">
          <el-button type="info" @click="showTransferPanel">
            <el-icon>
              <Connection />
            </el-icon>
            传输
          </el-button>

          <el-button @click="refreshFolder" :loading="loading">
            <el-icon>
              <Refresh />
            </el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="items.length === 0" class="empty-state">
        <el-empty description="此文件夹为空" />
      </div>

      <div v-else class="folder-grid">
        <div v-for="item in items" :key="item.key" class="folder-item"
          :class="{ 'selected': isEditMode && selectedItems.includes(item.key) }"
          @click="isEditMode ? toggleItemSelection(item) : handleItemClick(item)"
          @contextmenu.prevent="!isEditMode && handleContextMenu(item, $event)">
          <div v-if="isEditMode" class="selection-indicator">
            <el-checkbox :model-value="selectedItems.includes(item.key)"
              @change="(val) => handleCheckboxChange(item, val)" @click.stop />
          </div>

          <!-- 文件夹 -->
          <template v-if="item.type === 'folder'">
            <el-icon class="item-icon">
              <Folder />
            </el-icon>
            <div class="item-name">{{ item.nickname || item.name }}</div>
          </template>

          <!-- 视频 -->
          <template v-else-if="item.type === 'video'">
            <div class="video-thumbnail">
              <img v-if="item.thumbnailUrl" :src="item.thumbnailUrl" class="thumbnail" alt="视频缩略图">
              <el-icon v-else class="item-icon">
                <VideoCamera />
              </el-icon>
            </div>
            <div class="item-name">{{ item.nickname || item.name }}</div>
          </template>

          <!-- 图片 -->
          <template v-else-if="item.type === 'image'">
            <div class="image-thumbnail">
              <img v-if="item.thumbnailUrl" :src="item.thumbnailUrl" class="thumbnail" alt="图片缩略图"
                @error="handleImageError(item)">
              <el-icon v-else class="item-icon">
                <Picture />
              </el-icon>
            </div>
            <div class="item-name">{{ item.nickname || item.name }}</div>
          </template>

          <!-- 其他文件 -->
          <template v-else>
            <el-icon class="item-icon">
              <Document />
            </el-icon>
            <div class="item-name">{{ item.nickname || item.name }}</div>
          </template>
        </div>
      </div>
    </div>
  </div>

  <!-- 新建文件夹对话框 -->
  <el-dialog v-model="createFolderDialogVisible" title="新建文件夹" width="400px">
    <el-form :model="folderForm" @submit.prevent="createFolder">
      <el-form-item label="文件夹名称" :rules="[{ required: true, message: '请输入文件夹名称', trigger: 'blur' }]">
        <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" autofocus ref="folderNameInput" />
      </el-form-item>
      <div class="el-form__tip" style="color: #909399; font-size: 12px; margin-bottom: 15px;">
        注意：以下字符不能用于文件夹名称: \ / : * ? " < &gt; | </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="createFolderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createFolder" :loading="creatingFolder">
          创建
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 右键菜单 -->
  <el-dialog v-model="dialogVisible" title="编辑元数据" width="500px">
    <el-form :model="editForm" label-width="100px">
      <el-form-item label="名称">
        <el-input v-model="editForm.nickname" placeholder="请输入自定义名称" />
      </el-form-item>

      <el-form-item label="缩略图" v-if="editForm.type !== 'folder'">
        <el-upload class="thumbnail-uploader" action="#" :http-request="uploadThumbnail" :show-file-list="false"
          :before-upload="beforeThumbnailUpload">
          <img v-if="thumbnailPreview" :src="thumbnailPreview" class="thumbnail-preview" />
          <el-icon v-else class="thumbnail-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        <div class="el-upload__tip">
          请上传图片作为缩略图
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveMetadata" :loading="saving">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Folder, Document, Picture, VideoCamera, Refresh,
  Plus, Upload, Edit, Delete, FolderAdd, Connection
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const loading = ref(false)
const items = ref([])
const currentPrefix = ref('')
const rootDirectory = ref('')

// 编辑对话框
const dialogVisible = ref(false)
const editForm = ref({
  id: null,
  cosKey: '',
  nickname: '',
  type: ''
})
const thumbnailPreview = ref('')
const thumbnailFile = ref(null)
const saving = ref(false)

// 编辑模式相关
const isEditMode = ref(false)
const selectedItems = ref([])

// 新建文件夹相关
const createFolderDialogVisible = ref(false)
const folderForm = ref({
  name: ''
})
const creatingFolder = ref(false)
const folderNameInput = ref(null)

// 计算面包屑路径
const breadcrumbParts = computed(() => {
  if (!currentPrefix.value) return []

  // 如果配置了根目录，需要从当前路径中去除根目录部分
  let parts = currentPrefix.value.split('/').filter(Boolean)

  // 如果有根目录配置，去掉与根目录相关的部分
  if (rootDirectory.value) {
    const rootParts = rootDirectory.value.split('/').filter(Boolean)
    if (rootParts.length > 0) {
      // 检查当前路径是否包含根目录路径
      const rootPathMatch = rootParts.every((part, index) => parts[index] === part)
      if (rootPathMatch) {
        // 去掉根目录部分
        parts = parts.slice(rootParts.length)
      }
    }
  }

  return parts.map((part, index) => {
    // 构建完整路径（不是相对路径）
    let path = ''
    if (rootDirectory.value) {
      // 如果有根目录，需要保证路径包含根目录
      const rootParts = rootDirectory.value.split('/').filter(Boolean)
      // 构建直到当前部分的完整路径
      const fullParts = [...rootParts, ...parts.slice(0, index + 1)]
      path = fullParts.join('/')
    } else {
      // 构建直到当前部分的完整路径
      path = parts.slice(0, index + 1).join('/')
    }

    console.log(`面包屑项目 ${index}:`, { name: part, path });
    return { name: part, path }
  })
})

// 获取当前文件夹内容
const fetchFolderContents = async () => {
  loading.value = true
  try {
    const prefix = route.params.prefix || ''
    console.log('获取文件夹内容，前缀:', prefix)

    // 检查是否在缩略图文件夹内
    const isThumbnailFolder = prefix.includes('/thumbnail/') || prefix === 'thumbnail'
    if (isThumbnailFolder) {
      console.log('当前在缩略图文件夹内，不会生成新的缩略图')
    }

    const response = await axios.get('/api/cos/list', {
      params: { prefix }
    })

    if (response.data.success) {
      items.value = response.data.data
      currentPrefix.value = response.data.currentPrefix
      rootDirectory.value = response.data.rootDirectory || ''
      console.log('获取到的项目:', items.value)
      console.log('当前前缀:', currentPrefix.value)
      console.log('根目录设置:', rootDirectory.value)

      // 如果是在thumbnail文件夹内，显示提示
      if (response.data.isThumbnailFolder) {
        ElMessage({
          message: '您正在浏览缩略图文件夹，此文件夹中的图片不会再生成缩略图',
          type: 'info',
          duration: 5000
        })
      }

      // 检查有哪些项目带有缩略图
      const itemsWithThumbnails = items.value.filter(item => item.thumbnailUrl)
      console.log('带缩略图的项目数量:', itemsWithThumbnails.length)
      if (itemsWithThumbnails.length > 0) {
        console.log('带缩略图的项目:', itemsWithThumbnails)
      }
    } else {
      ElMessage.error('获取文件夹内容失败')
    }
  } catch (error) {
    console.error('获取文件夹内容失败:', error)
    ElMessage.error('获取文件夹内容失败')
  } finally {
    loading.value = false
  }
}

// 刷新当前文件夹
const refreshFolder = () => {
  fetchFolderContents()
}

// 处理面包屑导航项点击
const getBreadcrumbLink = (part, index) => {
  // 使用encodeURIComponent确保URL中的特殊字符被正确编码
  const encodedPath = encodeURIComponent(part.path);
  console.log(`构建面包屑链接 ${index}:`, {
    原始路径: part.path,
    编码路径: encodedPath,
    完整链接: `/folder/${encodedPath}`
  });
  return {
    name: 'folder',
    params: {
      prefix: part.path // 不在这里编码，让路由处理编码
    }
  };
}

// 处理项目点击
const handleItemClick = (item) => {
  if (item.type === 'folder') {
    console.log('点击文件夹，导航到:', item.key);
    router.push({
      name: 'folder',
      params: { prefix: item.key }
    });
  } else {
    console.log('点击文件，导航到预览页:', item.key);
    router.push({
      name: 'preview',
      params: { key: item.key } // 不在这里编码，让路由处理编码
    });
  }
}

// 处理右键菜单
const handleContextMenu = (item, event) => {
  // 如果是文件，不是文件夹，弹出菜单提供下载选项
  if (item.type !== 'folder') {
    ElMessageBox.confirm(
      '请选择操作',
      '文件操作',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '下载',
        cancelButtonText: '编辑信息',
        type: 'info'
      }
    ).then(() => {
      // 下载文件
      downloadFile(item);
    }).catch((action) => {
      if (action === 'cancel') {
        // 编辑信息
        // 检查是否是缩略图文件夹内的项目
        const isThumbnailItem = item.key.includes('/thumbnail/') || item.key.startsWith('thumbnail/')

        editForm.value = {
          id: item.id,
          cosKey: item.key,
          nickname: item.nickname || item.name,
          type: item.type
        }
        thumbnailPreview.value = item.thumbnailUrl || ''

        // 如果是在缩略图文件夹内且是图片，显示警告
        if (isThumbnailItem && item.type === 'image') {
          ElMessage({
            message: '注意：不建议为缩略图文件夹内的图片设置缩略图，这可能导致无限循环',
            type: 'warning',
            duration: 5000
          })
        }

        dialogVisible.value = true
      }
    });
  } else {
    // 对于文件夹，直接打开编辑对话框
    editForm.value = {
      id: item.id,
      cosKey: item.key,
      nickname: item.nickname || item.name,
      type: item.type
    }
    thumbnailPreview.value = item.thumbnailUrl || ''
    dialogVisible.value = true
  }
}

// 下载文件
const downloadFile = (file) => {
  const fileName = file.name;
  const key = file.key;
  const size = file.size || 0;

  // 添加到传输管理器
  let taskId = null;

  // 优先使用全局传输管理器
  if (window.transferManager) {
    console.log('使用全局传输管理器添加下载任务');
    taskId = window.transferManager.addTask({
      fileName,
      type: 'download',
      totalSize: size,
      progress: 0,
      status: 'waiting'
    });

    // 更新任务状态
    window.transferManager.updateTask(taskId, {
      status: 'running'
    });
  } else if (proxy && proxy.$transferManager) {
    console.log('使用Vue实例传输管理器添加下载任务');
    taskId = proxy.$transferManager.addTask({
      fileName,
      type: 'download',
      totalSize: size
    });

    // 更新任务状态
    proxy.$transferManager.updateTask(taskId, {
      status: 'running'
    });
  } else {
    console.warn('找不到传输管理器，无法添加下载任务');
  }

  axios.get(`/api/cos/download?key=${encodeURIComponent(key)}`, {
    responseType: 'blob'
  }).then(response => {
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 完成任务
    if (taskId) {
      // 优先使用全局传输管理器
      if (window.transferManager) {
        window.transferManager.completeTask(taskId, true);
      } else if (proxy && proxy.$transferManager) {
        proxy.$transferManager.completeTask(taskId, true);
      }
    }

    ElMessage.success('下载成功');
  }).catch(error => {
    console.error('下载失败', error);

    // 更新任务状态
    if (taskId) {
      const errorMsg = error.message || '下载失败';
      // 优先使用全局传输管理器
      if (window.transferManager) {
        window.transferManager.completeTask(taskId, false, errorMsg);
      } else if (proxy && proxy.$transferManager) {
        proxy.$transferManager.completeTask(taskId, false, errorMsg);
      }
    }

    ElMessage.error('下载失败：' + (error.message || '未知错误'));
  });
};

// 缩略图上传前验证
const beforeThumbnailUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('缩略图必须是图片格式!')
    return false
  }

  if (!isLt2M) {
    ElMessage.error('缩略图大小不能超过 2MB!')
    return false
  }

  thumbnailFile.value = file

  // 预览缩略图
  const reader = new FileReader()
  reader.onload = (e) => {
    thumbnailPreview.value = e.target.result
  }
  reader.readAsDataURL(file)

  return false // 阻止自动上传
}

// 自定义上传方法
const uploadThumbnail = () => {
  // 这里不做任何事情，因为我们在保存时一起上传
}

// 保存元数据
const saveMetadata = async () => {
  saving.value = true
  try {
    // 检查是否是缩略图文件夹内的项目
    const isThumbnailItem = editForm.value.cosKey.includes('/thumbnail/') ||
      editForm.value.cosKey.startsWith('thumbnail/')

    // 如果要为缩略图文件夹内的图片上传缩略图，显示警告并拒绝
    if (isThumbnailItem && thumbnailFile.value && editForm.value.type === 'image') {
      ElMessage.error('不能为缩略图文件夹内的图片设置缩略图，这会导致无限循环')
      saving.value = false
      return
    }

    const formData = new FormData()
    formData.append('cosKey', editForm.value.cosKey)
    formData.append('nickname', editForm.value.nickname)
    formData.append('type', editForm.value.type)

    if (thumbnailFile.value) {
      formData.append('thumbnail', thumbnailFile.value, 'thumbnail.png')
    }

    const response = await axios.post('/api/metadata/update', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.success) {
      ElMessage.success('元数据更新成功')
      dialogVisible.value = false
      refreshFolder()
    } else {
      ElMessage.error(response.data.message || '元数据更新失败')
    }
  } catch (error) {
    console.error('保存元数据失败:', error)
    ElMessage.error('保存元数据失败')
  } finally {
    saving.value = false
  }
}

// 处理图片加载错误
const handleImageError = async (item) => {
  console.error('缩略图加载失败:', item.key)

  // 如果是图片类型，尝试请求生成缩略图
  if (item.type === 'image') {
    try {
      const response = await axios.get(`/api/cos/thumbnail/${encodeURIComponent(item.key)}`)
      if (response.data.success && response.data.thumbnailUrl) {
        console.log('成功获取新的缩略图URL:', response.data.thumbnailUrl)
        // 更新项目的缩略图URL
        const index = items.value.findIndex(i => i.key === item.key)
        if (index !== -1) {
          items.value[index].thumbnailUrl = response.data.thumbnailUrl
        }
      }
    } catch (error) {
      console.error('请求生成缩略图失败:', error)
    }
  }
}

// 切换编辑模式
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value
  if (!isEditMode.value) {
    // 退出编辑模式时清空选择
    selectedItems.value = []
    // 重置所有项目的选中状态
    items.value.forEach(item => {
      item.selected = false
    })
  }
}

// 处理复选框变化事件
const handleCheckboxChange = (item, checked) => {
  console.log('复选框状态变化:', item.key, checked)
  if (checked) {
    // 添加到选中列表
    if (!selectedItems.value.includes(item.key)) {
      selectedItems.value.push(item.key)
    }
  } else {
    // 从选中列表中移除
    const index = selectedItems.value.indexOf(item.key)
    if (index !== -1) {
      selectedItems.value.splice(index, 1)
    }
  }
  // 同步更新项目的选中状态
  item.selected = checked
}

// 切换项目选择状态
const toggleItemSelection = (item) => {
  // 更新选中状态
  const isSelected = selectedItems.value.includes(item.key)
  const newState = !isSelected

  if (newState) {
    // 如果选中，添加到选中列表
    if (!selectedItems.value.includes(item.key)) {
      selectedItems.value.push(item.key)
    }
  } else {
    // 如果取消选中，从选中列表中移除
    const index = selectedItems.value.indexOf(item.key)
    if (index !== -1) {
      selectedItems.value.splice(index, 1)
    }
  }

  // 同步更新项目的选中状态
  item.selected = newState
}

// 确认删除选中项目
const confirmDelete = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要删除的项目')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedItems.value.length} 个项目吗？此操作不可撤销！`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteSelectedItems()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 删除选中的项目
const deleteSelectedItems = async () => {
  loading.value = true
  try {
    const response = await axios.post('/api/cos/delete', {
      keys: selectedItems.value
    })

    if (response.data.success) {
      ElMessage.success(`已成功删除 ${selectedItems.value.length} 个项目`)
      // 清空选中列表
      selectedItems.value = []
      // 刷新文件夹内容
      fetchFolderContents()
      // 退出编辑模式
      isEditMode.value = false
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除项目失败:', error)
    ElMessage.error('删除项目失败')
  } finally {
    loading.value = false
  }
}

// 上传文件
const uploadFile = async (options) => {
  // 获取服务器配置的文件大小限制 (3GB，与后端保持一致)
  const maxFileSize = 3000 * 1024 * 1024; // 默认3GB

  const file = options.file;

  // 检查文件大小是否超过限制
  if (file.size > maxFileSize) {
    ElMessage.error(`文件大小超过限制，最大允许 ${maxFileSize / (1024 * 1024)}MB`);
    if (options.onError) options.onError('文件大小超过限制');
    return;
  }

  // 提示用户大文件上传可能需要较长时间
  if (file.size > 50 * 1024 * 1024) { // 如果文件大于50MB
    ElMessage({
      message: `您正在上传较大的文件(${(file.size / (1024 * 1024)).toFixed(2)}MB)，上传过程可能需要较长时间，请耐心等待`,
      type: 'warning',
      duration: 8000
    });
  }

  // 构建目标路径
  let targetPath = currentPrefix.value;
  if (targetPath.endsWith('/')) {
    targetPath += file.name;
  } else {
    targetPath += '/' + file.name;
  }

  // 添加到传输管理器
  let taskId = null;
  const controller = new AbortController();

  // 优先使用全局传输管理器
  if (window.transferManager) {
    console.log('使用全局传输管理器添加上传任务');
    taskId = window.transferManager.addTask({
      fileName: file.name,
      type: 'upload',
      totalSize: file.size,
      progress: 0,
      status: 'waiting',
      onCancel: () => controller.abort()
    });

    // 更新任务状态
    window.transferManager.updateTask(taskId, {
      status: 'running'
    });
  } else if (proxy && proxy.$transferManager) {
    console.log('使用Vue实例传输管理器添加上传任务');
    taskId = proxy.$transferManager.addTask({
      fileName: file.name,
      type: 'upload',
      totalSize: file.size,
      onCancel: () => controller.abort()
    });

    // 更新任务状态
    proxy.$transferManager.updateTask(taskId, {
      status: 'running'
    });
  } else {
    console.warn('找不到传输管理器，无法添加上传任务');
  }

  const formData = new FormData();
  formData.append('file', file);
  formData.append('prefix', targetPath);

  try {
    const response = await axios.post('/api/cos/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);

          // 更新传输管理器进度
          if (taskId) {
            if (window.transferManager) {
              window.transferManager.updateTask(taskId, { progress: percentCompleted });
            } else if (proxy && proxy.$transferManager) {
              proxy.$transferManager.updateTask(taskId, { progress: percentCompleted });
            }
          }

          // 如果有进度回调，调用它
          if (options.onProgress) {
            options.onProgress({ percent: percentCompleted });
          }
        }
      },
      signal: controller.signal,
      // 增加超时时间，大文件需要更长的上传时间
      timeout: 3600000 // 1小时
    });

    if (response.data.success) {
      // 更新传输任务状态
      if (taskId) {
        if (window.transferManager) {
          window.transferManager.completeTask(taskId, true);
        } else if (proxy && proxy.$transferManager) {
          proxy.$transferManager.completeTask(taskId, true);
        }
      }

      ElMessage.success('文件上传成功');
      if (options.onSuccess) options.onSuccess();
      // 刷新文件夹内容
      refreshFolder();
    } else {
      // 更新传输任务状态
      if (taskId) {
        const errorMsg = response.data.message || '上传失败';
        if (window.transferManager) {
          window.transferManager.completeTask(taskId, false, errorMsg);
        } else if (proxy && proxy.$transferManager) {
          proxy.$transferManager.completeTask(taskId, false, errorMsg);
        }
      }

      ElMessage.error(response.data.message || '上传失败');
      if (options.onError) options.onError('上传失败');
    }
  } catch (error) {
    console.error('上传文件失败:', error);

    let errorMsg = '上传文件失败';
    if (error.code === 'ECONNABORTED') {
      errorMsg = '上传超时，请尝试上传小一些的文件';
    } else if (error.response && error.response.status === 413) {
      errorMsg = '文件大小超过服务器限制';
    } else {
      errorMsg = '上传文件失败: ' + (error.response?.data?.message || error.message);
    }

    // 更新传输任务状态
    if (taskId) {
      if (window.transferManager) {
        window.transferManager.completeTask(taskId, false, errorMsg);
      } else if (proxy && proxy.$transferManager) {
        proxy.$transferManager.completeTask(taskId, false, errorMsg);
      }
    }

    ElMessage.error(errorMsg);
    if (options.onError) options.onError(errorMsg);
  }
};

// 显示新建文件夹对话框
const showCreateFolderDialog = () => {
  folderForm.value.name = ''
  createFolderDialogVisible.value = true
  // 在下一个tick聚焦到输入框
  nextTick(() => {
    if (folderNameInput.value) {
      folderNameInput.value.focus()
    }
  })
}

// 创建文件夹
const createFolder = async () => {
  // 验证文件夹名称
  if (!folderForm.value.name.trim()) {
    ElMessage.warning('请输入文件夹名称')
    return
  }

  creatingFolder.value = true
  try {
    const response = await axios.post('/api/cos/folder', {
      prefix: currentPrefix.value,
      folderName: folderForm.value.name.trim()
    })

    if (response.data.success) {
      ElMessage.success('文件夹创建成功')
      createFolderDialogVisible.value = false
      // 刷新文件夹内容
      refreshFolder()
    } else {
      ElMessage.error(response.data.message || '创建文件夹失败')
    }
  } catch (error) {
    console.error('创建文件夹失败:', error)
    ElMessage.error('创建文件夹失败')
  } finally {
    creatingFolder.value = false
  }
}

// 显示传输面板
const showTransferPanel = () => {
  console.log('显示传输面板按钮被点击');

  try {
    // 尝试方法1：使用window全局对象
    if (window.transferManager) {
      console.log('使用window.transferManager显示传输面板');

      // 先检查方法是否存在
      if (typeof window.transferManager.showPanel === 'function') {
        window.transferManager.showPanel();
        return;
      } else if (typeof window.transferManager.showTransferPanel === 'function') {
        console.log('使用showTransferPanel替代方法');
        window.transferManager.showTransferPanel();
        return;
      } else {
        console.warn('传输管理器缺少showPanel和showTransferPanel方法');
        console.log('可用方法:', Object.keys(window.transferManager));
      }
    } else {
      console.warn('window.transferManager未定义');
    }

    // 尝试方法2：分发自定义事件
    console.log('尝试分发自定义事件');
    window.dispatchEvent(new CustomEvent('show-transfer-panel'));

    // 尝试方法3：使用Vue实例方法
    if (proxy && proxy.$transferManager) {
      console.log('使用Vue实例方法显示传输面板');

      if (typeof proxy.$transferManager.showPanel === 'function') {
        proxy.$transferManager.showPanel();
      } else if (typeof proxy.$transferManager.showTransferPanel === 'function') {
        proxy.$transferManager.showTransferPanel();
      } else {
        console.warn('Vue实例传输管理器缺少显示面板方法');
        console.log('可用方法:', Object.keys(proxy.$transferManager));
      }
    } else {
      console.warn('未找到传输管理器');
    }
  } catch (error) {
    console.error('显示传输面板出错:', error);

    // 最后的备用方案：直接修改DOM
    try {
      const transferManagerEl = document.getElementById('global-transfer-manager');
      if (transferManagerEl && transferManagerEl.__vueParentComponent && transferManagerEl.__vueParentComponent.ctx) {
        console.log('尝试直接访问DOM中的传输管理器');
        const tmComponent = transferManagerEl.__vueParentComponent.ctx;
        if (typeof tmComponent.showTransferPanel === 'function') {
          tmComponent.showTransferPanel();
        }
      }
    } catch (e) {
      console.error('备用方案也失败了:', e);
    }
  }
};

// 监听路由变化
watch(
  () => route.params.prefix,
  () => {
    fetchFolderContents()
  }
)

onMounted(() => {
  fetchFolderContents()
})
</script>

<style scoped>
.folder-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-actions {
  display: flex;
  gap: 10px;
}

.right-actions {
  display: flex;
  gap: 10px;
}

.upload-button {
  display: inline-block;
}

.loading-state {
  padding: 20px;
}

.folder-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.folder-item:hover {
  background-color: #f0f9ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.folder-item.selected {
  background-color: #ecf5ff;
  border-color: #409eff;
  box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.3);
}

.selection-indicator {
  position: absolute;
  top: 5px;
  left: 5px;
  z-index: 2;
}

.thumbnail-uploader {
  width: 120px;
  height: 90px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.thumbnail-uploader:hover {
  border-color: #409EFF;
}

.thumbnail-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.thumbnail-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>